from datetime import datetime
from django.core.cache import cache
from django.utils import simplejson
from socialbar import profileControl
from socialbar.constants import DEALSSTATUS, keyFromValue
from socialbar.models import Bar, Greeting, Deal
from django.template.loader import render_to_string
from django.http import HttpResponse
import logging
import math
import urllib 

MEMCACHE_COORDINATE = 'coordinate'

def distance_on_unit_sphere(lat1, long1, lat2, long2):
  degrees_to_radians = math.pi / 180.0

  phi1 = (90.0 - lat1) * degrees_to_radians
  phi2 = (90.0 - lat2) * degrees_to_radians

  theta1 = long1 * degrees_to_radians
  theta2 = long2 * degrees_to_radians

  cos = (math.sin(phi1) * math.sin(phi2) * math.cos(theta1 - theta2) + 
         math.cos(phi1) * math.cos(phi2))
  arc = math.acos(cos)

  return int(arc * 6353000)


def getAllBars(request):
  bars = Bar.objects.all()
  list(bars)
  
  for i in range(0, bars.count()):
    bars[i].url = unicode_urlencode('/bar/' + bars[i].name)
    if request.session.has_key('coordinate_latitude'):
      bars[i].distance = distance_on_unit_sphere(
          float(request.session['coordinate_latitude']),
          float(request.session['coordinate_longitude']),
          float(bars[i].latitude), float(bars[i].longitude))
  return bars

def getBar(barName):
  barName = urllib.unquote_plus(barName)
  logging.debug('get Bar ' + barName)
  bars = Bar.objects.filter(name=barName)
  return bars[0]

def unicode_urlencode(value):
    try: 
        return urllib.quote(value) 
    except Exception: 
        return urllib.quote(value.encode("utf-8")) 



def useDeal(request):
  logging.debug('USEDEAL')
  if request.user.is_authenticated() is False:
    return simplejson.dumps({'error' : 'notConnected',
                      'msg' : 'Merci de vous connecter pour pouvoir utiliser des coupons'})
  dealsBought = Deal.objects.filter(user=request.user,
                           status=keyFromValue(DEALSSTATUS, 'Bought'))
   
  if len(dealsBought) == 0:
    return simplejson.dumps({'error' : 'noDealsBought',
        'msg' : 'Merci de vous procurer des coupons.'})

  dealsBought[0].status = keyFromValue(DEALSSTATUS, 'Used')
  dealsBought[0].usedDate = datetime.now()
  bar = Bar.objects.get(id=request.POST['idBar'])
  dealsBought[0].bar = bar
  dealsBought[0].save()
  
  dealsUsedCurrentBar = Deal.objects.filter(user=request.user,
                           status=keyFromValue(DEALSSTATUS, 'Used'),
                           bar = bar)
  return simplejson.dumps({'success' : 'dealUsed',
      'data' : {'dealBoughtCount' : len(dealsBought) - 1,
                'dealsUsedCurrentBarCount' : len(dealsUsedCurrentBar)  }})  

def saveCoordinate(request):
  latitude = request.POST['latitude']
  longitude = request.POST['longitude']
  logging.debug('Handler : save coordinate' + longitude + ' and ' + latitude)
  request.session['coordinate_latitude'] = latitude 
  request.session['coordinate_longitude'] = longitude
  render = render_to_string('socialbar/listBar.html',
      {'bars': getAllBars(request)})
  json_response = simplejson.dumps({"success" : "OK",
                                    "page": render})
  request.session.set_expiry(3)
  return HttpResponse(json_response)

def saveCurrentBarSession(request, barName):
  request.session['currentBar'] = barName
  

  
  
  
